package co.yixiang.gateway.service.impl;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;

import co.yixiang.gateway.service.ValidateCodeService;
import com.alibaba.csp.sentinel.util.IdUtil;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import co.yixiang.common.core.constant.Constants;
import co.yixiang.common.core.exception.CaptchaException;
import co.yixiang.common.core.utils.IdUtils;
import co.yixiang.common.core.utils.StringUtils;
import co.yixiang.common.core.utils.sign.Base64;
import co.yixiang.common.core.web.domain.AjaxResult;
import co.yixiang.common.redis.service.RedisService;

/**
 * 验证码实现处理
 *
 * @author yshop
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService
{


    @Autowired
    private RedisService redisService;


    /**
     * 生成验证码
     */
    @Override
    public AjaxResult createCapcha() throws IOException, CaptchaException
    {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;


        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result ="";
        try {
            result = new Double(Double.parseDouble(captcha.text())).intValue()+"";
        }catch (Exception e){
            result = captcha.text();
        }

        redisService.setCacheObject(verifyKey, result, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 验证码信息

        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", captcha.toBase64());

        return ajax;
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCapcha(String code, String uuid) throws CaptchaException
    {
        if (StringUtils.isEmpty(code))
        {
            throw new CaptchaException("验证码不能为空");
        }
        if (StringUtils.isEmpty(uuid))
        {
            throw new CaptchaException("验证码已失效");
        }
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisService.getCacheObject(verifyKey);
        redisService.deleteObject(verifyKey);

        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException("验证码错误");
        }
    }
}
